<template>
    <div class="map-container">
        <!-- 嵌入google map -->
        <webview :src="_google_map_url" style="width: 100%; height: 100%; border: none" ref="webview" id="webview">
        </webview>
        <!-- 透明矩形框 -->
        <div v-if="_show_rect" class="overlay-rect" :style="{
            left: `${_rect.left}px`,
            top: `${_rect.top}px`,
            right: `${_rect.right}px`,
            bottom: `${_rect.bottom}px`,
        }"></div>
    </div>
</template>

<script setup>
import API from '@/js/api';
import { onMounted, onUnmounted, ref, nextTick, getCurrentInstance } from 'vue';
import { parseGoogleMapsUrl } from '@/js/utils/mapUtils';
import { generateSpiralCoordinates } from '@/js/utils/captureUtils.js';
const { proxy } = getCurrentInstance();

// 定义嵌入google map的vue成员变量
// `https://www.google.com/maps/@${lat},${lng},${zoom}z/data=!5m1!1e3`; 1e3 为卫星图模式
const webview = ref(null);
const _google_map_url = ref('');
const _zoom = ref(19);
const _show_rect = ref(true);
const _rect = ref({
    left: 100,
    top: 100,
    right: 100,
    bottom: 100,
});

async function capture() {
    // 获取当前的url地址
    const webview = proxy.$refs.webview;
    const currentUrl = webview.getURL();
    const mapParams = parseGoogleMapsUrl(currentUrl);
    console.log('currentUrl = ', currentUrl);
    console.log('mapParams = ', mapParams);

    // 获取 DPI 缩放比例
    const scaleFactor = window.devicePixelRatio || 1;
    console.log(`scaleFactor = ${scaleFactor}`);
    let result = await API.local.invoke(
        'CaptureMap',
        {
            capture: JSON.stringify({
                lat: mapParams.latitude,
                lng: mapParams.longitude,
                alt: mapParams.altitude,
                zoom: _zoom.value,
                crop: {
                    left: 100,
                    top: 100,
                    right: 100,
                    bottom: 100
                },
                scaleFactor: scaleFactor
            })
        }
    );
    return result;
}

async function onCaptureCallback(data) {
    // 关闭当前矩形框展示
    _show_rect.value = false;
    await nextTick();

    // 调用实际截图的接口
    let result = await capture();
    if (result.code === 0) {
        ElMessage.success({
            message: result.msg,
            duration: 1000
        });
    } else {
        ElMessage.error({
            message: result.msg,
            duration: 1000
        });
    }

    // 打开当前矩形框展示
    _show_rect.value = true;
    await nextTick();
}

async function onDragCallback(data) {
    // 关闭当前矩形框展示
    _show_rect.value = false;
    await nextTick();

    // 获取窗口的宽高
    const width = window.innerWidth;
    const height = window.innerHeight;

    // 获取螺旋轨迹，方向移动鼠标
    const layer = 2;
    const spiralCoordinates = generateSpiralCoordinates(layer);
    // console.log(spiralCoordinates);
    let coord0 = { x: 0, y: 0 };
    let result = await capture();
    console.log(result);
    if (result.code !== 0) {
        ElMessage.error({
            message: result.msg,
            duration: 1000
        });
        return;
    }

    let coord1 = null;
    for (let i = 1; i < spiralCoordinates.length; i++) {
        // 每次移动设置到中心点
        let x1 = width / 2;
        let y1 = height / 2;
        let x2 = width / 2;
        let y2 = height / 2;

        // 根据螺旋轨迹获取对应的移动坐标
        coord1 = spiralCoordinates[i];
        if (coord0.x === coord1.x) {
            // 在纵轴方向移动
            if (coord0.y - coord1.y < 0) {
                y1 = height / 4;
                y2 = height * 3 / 4;
            } else {
                y1 = height * 3 / 4;
                y2 = height / 4;
            }
        } else if (coord0.y === coord1.y) {
            // 在横轴方向移动
            if (coord0.x - coord1.x < 0) {
                x1 = width / 4;
                x2 = width * 3 / 4;
            } else {
                x1 = width * 3 / 4;
                x2 = width / 4;
            }
        } else {
            console.error(`生成的螺旋轨迹有问题,coord0 = ${coord0.x}, ${coord0.y}, coord1 = ${coord1.x}, ${coord1.y}`);
        }
        coord0 = spiralCoordinates[i];
        console.log(`x1=${x1}, y1=${y1}, x2=${x2}, y2=${y2}`);

        // 调用api实际移动
        let result = await API.invoke('SimulateDrag', {
            x1,
            y1,
            x2,
            y2,
        });
        console.log(result);

        // 调用api后等待一段时间，开始进行截图
        await new Promise(resolve => setTimeout(resolve, 500));
        result = await capture();
        console.log(result);
    }

    // 打开当前矩形框展示
    _show_rect.value = true;
    await nextTick();

    // 判断data是否存在并且mode=auto，则关闭窗口
    if (data && data.mode === 'auto') {
        let result = await API.local.invoke('CloseMapWnd', { mode: 'auto' });
        console.log(result);
    }
}

async function onWsMessage(message) {
    console.log('CaptureWnd::onWsMessage message = ', message);
    let data = JSON.parse(message);
    if (data.event === 'capture') {
        await onCaptureCallback(data);
    } else if (data.event === 'drag') {
        await onDragCallback(data);
    }
}

onMounted(async () => {
    // 获取窗口上的经纬度和zoom参数
    const urlParams = new URLSearchParams(window.location.search);
    let lat = urlParams.get('lat');
    let lng = urlParams.get('lng');
    let zoom = urlParams.get('zoom');
    let mode = urlParams.get('mode');
    _zoom.value = zoom;
    _google_map_url.value = `https://www.google.com/maps/@${lat},${lng},${zoom}z/data=!5m1!1e3`;

    // 捕捉到
    await nextTick();
    const webviewElement = webview.value;
    if (webviewElement) {
        // 在渲染进程的页面中
        document.addEventListener('mousedown', (event) => {
            // console.log('App.vue Mouse Down:', event.clientX, event.clientY);
            // 模拟鼠标按下
            webviewElement.sendInputEvent({
                type: 'mousedown',
                x: event.clientX,
                y: event.clientY,
                button: 'left',
            });
        });

        document.addEventListener('mousemove', (event) => {
            // console.log('App.vue Mouse Move:', event.clientX, event.clientY);
            // 模拟鼠标移动
            webviewElement.sendInputEvent({
                type: 'mousemove',
                x: event.clientX,
                y: event.clientY,
                button: 'left',
            });
        });

        document.addEventListener('mouseup', (event) => {
            // console.log('App.vue Mouse Up:', event.clientX, event.clientY);
            // 模拟鼠标释放
            webviewElement.sendInputEvent({
                type: 'mouseup',
                x: event.clientX,
                y: event.clientY,
                button: 'left',
            });
        });

        // webviewElement.addEventListener("did-navigate", handleUrlChange);
        webviewElement.addEventListener("did-finish-load", () => {
            console.log("Webview is ready");

            // 延迟 2 秒后执行脚本
            setTimeout(() => {
                const script = `
                    // 关闭标签显示
                    const labelButton = document.querySelector('button[jsaction="layerswitcher.intent.labels"]');
                    if (labelButton) {
                        labelButton.click();
                    }

                    // 隐藏对应的元素展示
                    const elementsToHide = [
                        '#gb',
                        '#omnibox-container',
                        '#assistive-chips',
                        'div.ztgaDb.fontBodySmall.LfygZc.widget-layer-shown',
                        'div.app-horizontal-widget-holder.Hk4XGb',
                        'div.app-vertical-widget-holder.Hk4XGb'
                    ];

                    elementsToHide.forEach(selector => {
                        const element = document.querySelector(selector);
                        if (element) {
                            element.style.display = 'none';
                        }
                    });
                `;

                // 执行脚本
                webviewElement.executeJavaScript(script);

                // 开始自动化操作
                console.log(mode);
                if (mode === 'auto') {
                    onDragCallback({ mode: 'auto' });
                }
            }, 1000);
        });
    }
});

onUnmounted(() => {

});

defineExpose({ onWsMessage });

</script>


<style scoped>
.map-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
}

.overlay-rect {
    position: absolute;
    border: 2px solid red;
    background-color: rgba(255, 0, 0, 0.1);
    pointer-events: none;
}
</style>